//
//  TranslationWordController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/5/6.
//

import UIKit
import SnapKit
import Reusable
import AVFoundation

class TranslationWordController: BaseViewController {
    
    let synthesizer = AVSpeechSynthesizer()
    
    private lazy var cameraButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("生成语音并播放", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = .themeColor
        button.addTarget(self, action: #selector(cameraAction), for: .touchUpInside)
        view.addSubview(button)
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        synthesizer.delegate = self
        initNav()
        initUI()
    }
    
    
}

// MARK: - private
private extension TranslationWordController {
    
    func initNav() {
        navigationItem.title = "文字翻译"
    }
    
    func initUI() {
        let list = AVSpeechSynthesisVoice.speechVoices()
        
        list.forEach { voice in
            xLog("********** 播报员 **********")
            xLog("language \(voice.language)")
            xLog("name \(voice.name)")
            xLog("gender \(voice.gender)")
        }
        
        
        cameraButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-xIphoneBottomSafeHeight)
            make.size.equalTo(CGSize(width: 100, height: 50))
        }
        
    }
    
    
}

// MARK: - Action
extension TranslationWordController {
    
    @objc func cameraAction() {
        
        // 使用示例
        speakTextWithDelay(text: "被门夹过的核桃还能补脑么？被门夹过的核桃还能补脑么？", delay: 6)
        
    }
    
    
    
    func speakTextWithDelay(text: String, delay: TimeInterval) {
        let utterance = AVSpeechUtterance(string: text)
        // 设置语言，例如使用英语（美国）en-US, 中文 zh-Hans
        utterance.voice = AVSpeechSynthesisVoice(language: "zh-CN") // "zh-Hant-HK" 设置粤语
        // 设置语速 默认:0.5
        utterance.rate = AVSpeechUtteranceDefaultSpeechRate
        // 设置音调
        utterance.pitchMultiplier = 1.0
        // 设置音量
        utterance.volume = 1.0
        synthesizer.speak(utterance)
        
        let averageCharDuration: TimeInterval = 0.5 // 每个字符的平均朗读时间，单位为秒
        // 调整基于语速的朗读时间
        let totalDuration = TimeInterval(text.count) * averageCharDuration / Double(utterance.rate)
        // 播放文本并停顿2秒后停止
        DispatchQueue.main.asyncAfter(deadline: .now() + totalDuration) { [weak self] in
            xLog("停止")
            self?.synthesizer.stopSpeaking(at: .word)
        }
    }
    
}
extension TranslationWordController: AVSpeechSynthesizerDelegate {
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        xLog("didFinish 播放完")
        let res = synthesizer.stopSpeaking(at: .immediate)
        xLog("停止 : \(res ? "ok": "no")")
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
        print("didStart \(utterance)")
    }
    
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
        print("didCancel \(utterance)")
    }
}
